import {Component, OnInit} from '@angular/core';
import {Login} from "../../model/login";
import {HttpService} from "../../service/http.service";
import {AuthService} from "../../service/auth.service";
import {Router} from "@angular/router";
import {ApiPath} from "../../config/api-path";
import {TokenDt} from "../../model/tokenDt";
import {AlertController} from "@ionic/angular";


@Component({
  selector: 'app-login',
  templateUrl: './login-page.component.html',
  styleUrls: ['./login-page.component.scss'],
})
export class LoginPage implements OnInit {

  constructor(
    private HttpSrv: HttpService,
    private AuthSvc: AuthService,
    private router: Router,
    private alertCtrl: AlertController
  ) {
  }

  ngOnInit() {
  }

  info: Login = {
    userNameOrStuID: '',
    password: ''
  };

  submit() {
    console.debug(this.info);
    let msg = "出错了！请稍后再试！";
    this.HttpSrv.httpPost<TokenDt>(ApiPath.request.login, this.info).subscribe(
      res => {
        console.debug(res)
        if (res && res.hasOwnProperty("data") && res.data != null && res.data.hasOwnProperty("token")) {
          this.AuthSvc.setToken(res.data.token);
          this.router.navigate(['ynuer/help']).then(r => r);
          msg = "欢迎！"
        } else {
          if (res && res.hasOwnProperty("msg")) {
            msg = res.msg;
          }
        }
        this.showAlert(msg).then(r => null)
      })
    this.router.navigate(['user/login']).then(r => r);
  }

  async showAlert(msg: string) {
    let alert = await this.alertCtrl.create({
      message: msg,
      buttons: ["确定"]
    });
    await alert.present();
  }
}
